package org.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.example.common.Result;
import org.example.model.Article;
import org.example.service.ArticleService;
import org.example.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/article")
@CrossOrigin(origins = "*")
@Api(tags = "文章管理", description = "文章的创建、查询、修改和删除相关接口")
public class ArticleController {

    @Autowired
    private ArticleService articleService;
    
    @Autowired
    private FileUploadUtil fileUploadUtil;

    @PostMapping("/create")
    @ApiOperation(value = "创建并发布文章", notes = "创建一篇新文章并立即发布")
    public ResponseEntity<Article> createArticle(@ApiParam(value = "文章信息", required = true) @RequestBody Article article) {
        Article savedArticle = articleService.createArticle(article);
        return ResponseEntity.ok(savedArticle);
    }

    @PostMapping("/saveDraft")
    @ApiOperation(value = "保存文章草稿", notes = "保存文章草稿，不发布")
    public ResponseEntity<Article> saveDraft(@ApiParam(value = "文章草稿信息", required = true) @RequestBody Article article) {
        Article savedArticle = articleService.saveDraft(article);
        return ResponseEntity.ok(savedArticle);
    }

    @GetMapping("/list")
    @ApiOperation(value = "获取已发布文章列表", notes = "获取所有已发布的文章列表，按发布时间倒序排序")
    public ResponseEntity<Map<String, Object>> getArticleList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        List<Article> articles = articleService.getArticleList();
        
        // 计算分页
        int total = articles.size();
        int start = (page - 1) * pageSize;
        int end = Math.min(start + pageSize, total);
        List<Article> pagedArticles = articles.subList(start, end);
        
        Map<String, Object> response = new HashMap<>();
        response.put("list", pagedArticles);
        response.put("total", total);
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("data", response);
        result.put("msg", "获取成功");
        
        return ResponseEntity.ok(result);
    }
    
    @GetMapping("/all")
    @ApiOperation(value = "获取所有文章列表", notes = "获取所有文章列表，包括草稿，按更新时间倒序排序")
    public ResponseEntity<List<Article>> getAllArticles() {
        List<Article> articles = articleService.getAllArticles();
        return ResponseEntity.ok(articles);
    }
    
    @GetMapping("/drafts")
    @ApiOperation(value = "获取草稿列表", notes = "获取所有草稿文章，按更新时间倒序排序")
    public ResponseEntity<List<Article>> getDrafts() {
        List<Article> drafts = articleService.getDrafts();
        return ResponseEntity.ok(drafts);
    }

    @GetMapping("/detail/{id}")
    @ApiOperation(value = "获取文章详情", notes = "根据文章ID获取文章详情")
    public ResponseEntity<Map<String, Object>> getArticleDetail(@ApiParam(value = "文章ID", required = true) @PathVariable Long id) {
        Article article = articleService.getArticleById(id);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("data", article);
        result.put("msg", "获取成功");
        return ResponseEntity.ok(result);
    }

    @PutMapping("/update/{id}")
    @ApiOperation(value = "更新文章", notes = "更新现有文章的信息")
    public ResponseEntity<Article> updateArticle(
            @ApiParam(value = "文章ID", required = true) @PathVariable Long id,
            @ApiParam(value = "文章信息", required = true) @RequestBody Article article) {
        // 确保路径中的ID与文章对象的ID一致
        if (!id.equals(article.getId())) {
            return ResponseEntity.badRequest().build();
        }

        Article updatedArticle = articleService.updateArticle(article);
        return ResponseEntity.ok(updatedArticle);
    }
    
    @PutMapping("/publish/{id}")
    @ApiOperation(value = "发布草稿文章", notes = "将草稿状态的文章发布")
    public ResponseEntity<Article> publishDraft(
            @ApiParam(value = "文章ID", required = true) @PathVariable Long id) {
        // 先获取文章
        Article article = articleService.getArticleById(id);
        
        // 只有草稿可以发布
        if (!"draft".equals(article.getStatus())) {
            return ResponseEntity.badRequest().body(article);
        }
        
        // 设置为发布状态并更新
        article.setStatus("published");
        Article updatedArticle = articleService.updateArticle(article);
        return ResponseEntity.ok(updatedArticle);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除文章", notes = "根据文章ID删除文章")
    public ResponseEntity<Void> deleteArticle(@ApiParam(value = "文章ID", required = true) @PathVariable Long id) {
        articleService.deleteArticle(id);
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/upload-cover")
    @ApiOperation(value = "上传文章封面图", notes = "上传文章封面图片，返回图片URL")
    public ResponseEntity<String> uploadCoverImage(@RequestParam("file") MultipartFile file) {
        try {
            String url = fileUploadUtil.uploadArticleImage(file);
            return ResponseEntity.ok(url);
        } catch (IllegalArgumentException e) {
            // 参数错误，例如文件为空、格式不支持等
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("文件上传失败: " + e.getMessage());
        }
    }
} 